<?
if (!defined('SMF'))
	die('Hacking attempt...');
	
global $smcFunc, $txt, $scripturl, $user_info;
global $dbtables, $color_header, $color_line1, $color_line2;
global $dev_minedeflector_price, $dev_escapepod_price, $dev_fuelscoop_price, $dev_lssd_price;
global $colonist_price, $torpedo_price, $fighter_price, $armor_price;
global $dev_genesis_price, $dev_beacon_price, $dev_emerwarp_price, $dev_warpedit_price;
global $max_emerwarp, $allow_ibank, $inventory_factor, $upgrade_cost;
global $ore_price, $ore_delta, $ore_limit;
global $energy_price, $energy_delta, $energy_limit;
global $goods_price, $goods_delta, $goods_limit;
global $organics_price, $organics_delta, $organics_limit;
global $debug;

// Verify user login, if CheckLogin() returns false return to the calling script/function
if (CheckLogin() == false)
	return;

//-------------------------------------------------------------------------------------------------

// Get user info.
$result = $smcFunc['db_query']('', '
	SELECT *
	FROM {raw:db_ships}
	WHERE user_id = {int:user_id}
	LIMIT 1',
	array(
		'db_ships' => $dbtables['ships'],
		'user_id' => $user_info['id'],
	)
);
$playerinfo = $smcFunc['db_fetch_assoc']($result);
$smcFunc['db_free_result']($result);

// Get sector info.
$result = $smcFunc['db_query']('', '
	SELECT *
	FROM {raw:db_universe}
	WHERE sector_id = {int:sector}',
	array(
		'db_universe' => $dbtables['universe'],
		'sector' => $playerinfo['sector']
	)
);
$sectorinfo = $smcFunc['db_fetch_assoc']($result);
$smcFunc['db_free_result']($result);

// Get zone info.
$result = $smcFunc['db_query']('', '
	SELECT *
	FROM {raw:db_zones}
	WHERE zone_id = {int:sector}',
	array(
		'db_zones' => $dbtables['zones'],
		'sector' => $sectorinfo['zone_id']
	)
);
$zoneinfo = $smcFunc['db_fetch_assoc']($result);
$smcFunc['db_free_result']($result);

if ($zoneinfo['allow_trade'] == 'N')
{
	BigTitle($txt['bnt_no_trade']);
	echo $txt['bnt_no_trade_info'], '<p>';
	TextMainMenu();
	die();
}
elseif ($zoneinfo['allow_trade'] == 'L')
{
	if ($zoneinfo['corp_zone'] == 'N')
	{
		$result = $smcFunc['db_query']('', '
			SELECT team
			FROM {raw:db_ships}
			WHERE ship_id = {int:owner}',
			array(
				'db_ships' => $dbtables['ships'],
				'owner' => $zoneinfo['owner']
			)
		);
		$ownerinfo = $smcFunc['db_fetch_assoc']($result);
		$smcFunc['db_free_result']($result);

		if ($playerinfo['ship_id'] != $zoneinfo['owner'] && $playerinfo['team'] == 0 || $playerinfo['team'] != $ownerinfo['team'])
		{
			BigTitle($txt['bnt_no_trade']);
			echo $txt['bnt_no_trade_out'], '<p>';
			TextMainMenu();
			die();
		}
	}
	else
	{
		if ($playerinfo['team'] != $zoneinfo['owner'])
		{
			BigTitle($txt['bnt_no_trade']);
			echo $txt['bnt_no_trade_out'], '<p>';
			TextMainMenu();
			die();
		}
	}
}

BigTitle($txt['bnt_title_port']);

$color_red     = "red";
$color_green   = "#00FF00"; //light green
$trade_deficit = $txt['bnt_cost'] . ' : ';
$trade_benefit = $txt['bnt_profit'] . ' : ';


function BuildOneCol( $text = "&nbsp;", $align = "left" ) {
	echo '
		<tr>
		  <td colspan=99 align="', $align, '">"', $text, '"</td>
		</tr>
	';
}

function BuildTwoCol( $text_col1 = "&nbsp;", $text_col2 = "&nbsp;", $align_col1 = "left", $align_col2 = "left" ) {
	echo '
		<tr>
		  <td align="', $align_col1, '">"', $text_col1, '"</td>
		  <td align="', $align_col2, '">"', $text_col2, '"</td>
		</tr>
	';
}


function phpTrueDelta($futurevalue, $shipvalue)
{
	$tempval = $futurevalue - $shipvalue;
	return $tempval;
}

function phpChangeDelta($desiredvalue, $currentvalue)
{
	global $upgrade_cost;

	$Delta = 0;
	$DeltaCost = 0;
	$Delta = $desiredvalue - $currentvalue;

	while ($Delta > 0) 
	{
		$DeltaCost = $DeltaCost + mypw(2, $desiredvalue - $Delta); 
		$Delta = $Delta - 1;
	}
	$DeltaCost = $DeltaCost * $upgrade_cost;

	return $DeltaCost;
}

if ($playerinfo['turns'] < 1)
	echo $txt['bnt_trade_turnneed'], '<br><br>';
else
{
	if ($sectorinfo['port_type'] == "special")
	{
		// Check for debt information first thing, and if there is a debt halt the script.
		if (isLoanPending($playerinfo['ship_id']))
		{
			echo $txt['bnt_port_loannotrade'], '<p>';
			echo '<a href=',$scripturl,'?action=blacknova;sa=igb>', $txt['bnt_igb_term'], '</a><p>';
			TextMainMenu();
			die();
		}
		
		// Read in POST variables from port.php.
		// If we find that one of them is not set, assume there is a problem and halt the script.
		if (isset($_POST['hull_upgrade']))
			$hull_upgrade = $_POST['hull_upgrade'];
		else
			die();
		if (isset($_POST['engine_upgrade']))
			$engine_upgrade = $_POST['engine_upgrade'];
		else
			die();
		if (isset($_POST['power_upgrade']))
			$power_upgrade = $_POST['power_upgrade'];
		else
			die();
		if (isset($_POST['computer_upgrade']))
			$computer_upgrade = $_POST['computer_upgrade'];
		else
			die();
		if (isset($_POST['sensors_upgrade']))
			$sensors_upgrade = $_POST['sensors_upgrade'];
		else
			die();
		if (isset($_POST['beams_upgrade']))
			$beams_upgrade = $_POST['beams_upgrade'];
		else
			die();
		if (isset($_POST['armor_upgrade']))
			$armor_upgrade = $_POST['armor_upgrade'];
		else
			die();
		if (isset($_POST['cloak_upgrade']))
			$cloak_upgrade = $_POST['cloak_upgrade'];
		else
			die();
		if (isset($_POST['torp_launchers_upgrade']))
			$torp_launchers_upgrade = $_POST['torp_launchers_upgrade'];
		else
			die();
		if (isset($_POST['shields_upgrade']))
			$shields_upgrade = $_POST['shields_upgrade'];
		else
			die();
		if (isset($_POST['fighter_number']))
			$fighter_number = $_POST['fighter_number'];
		else
			die();
		if (isset($_POST['torpedo_number']))
			$torpedo_number = $_POST['torpedo_number'];
		else
			die();
		if (isset($_POST['armor_number']))
			$armor_number = $_POST['armor_number'];
		else
			die();
		if (isset($_POST['colonist_number']))
			$colonist_number = $_POST['colonist_number'];
		else
			die();
		if (isset($_POST['dev_genesis_number']))
			$dev_genesis_number = $_POST['dev_genesis_number'];
		else
			die();
		if (isset($_POST['dev_beacon_number']))
			$dev_beacon_number = $_POST['dev_beacon_number'];
		else
			die();
		if (isset($_POST['dev_emerwarp_number']))
			$dev_emerwarp_number = $_POST['dev_emerwarp_number'];
		else
			die();
		if (isset($_POST['dev_warpedit_number']))
			$dev_warpedit_number = $_POST['dev_warpedit_number'];
		else
			die();
		if (isset($_POST['dev_minedeflector_number']))
			$dev_minedeflector_number = $_POST['dev_minedeflector_number'];
		else
			die();
		
		// Escape Pod, Fuel Scoop and Last Ship Seen Device may or may not be POSTe'd
		if (isset($_POST['escapepod_purchase']))
			$escapepod_purchase = $_POST['escapepod_purchase'];
		else
			$escapepod_purchase = FALSE;
		if (isset($_POST['fuelscoop_purchase']))
			$fuelscoop_purchase = $_POST['fuelscoop_purchase'];
		else
			$fuelscoop_purchase = FALSE;
		if (isset($_POST['lssd_purchase']))
			$lssd_purchase = $_POST['lssd_purchase'];
		else
			$lssd_purchase = FALSE;
		
		$hull_upgrade_cost = 0;
		if ($hull_upgrade > $playerinfo['hull'])
		{
			$hull_upgrade_cost = phpChangeDelta($hull_upgrade, $playerinfo['hull']);
		}
		
	    $engine_upgrade_cost = 0;
	    if ($engine_upgrade > $playerinfo['engines'])
	    {
			$engine_upgrade_cost = phpChangeDelta($engine_upgrade, $playerinfo['engines']);
	    }
		
	    $power_upgrade_cost = 0;
	    if ($power_upgrade > $playerinfo['power'])
	    {
			$power_upgrade_cost = phpChangeDelta($power_upgrade, $playerinfo['power']);
	    }
	
	    $computer_upgrade_cost = 0;
	    if ($computer_upgrade > $playerinfo['computer'])
	    {
			$computer_upgrade_cost = phpChangeDelta($computer_upgrade, $playerinfo['computer']);
	    }
		
	    $sensors_upgrade_cost = 0;
	    if ($sensors_upgrade > $playerinfo['sensors'])
	    {
			$sensors_upgrade_cost = phpChangeDelta($sensors_upgrade, $playerinfo['sensors']);
	    }
		
	    $beams_upgrade_cost = 0;
	    if ($beams_upgrade > $playerinfo['beams'])
	    {
			$beams_upgrade_cost = phpChangeDelta($beams_upgrade, $playerinfo['beams']);
	    }
		
	    $armor_upgrade_cost = 0;
	    if ($armor_upgrade > $playerinfo['armor'])
	    {
			$armor_upgrade_cost = phpChangeDelta($armor_upgrade, $playerinfo['armor']);
	    }
		
	    $cloak_upgrade_cost = 0;
	    if ($cloak_upgrade > $playerinfo['cloak'])
	    {
			$cloak_upgrade_cost = phpChangeDelta($cloak_upgrade, $playerinfo['cloak']);
	    }
	
	    $torp_launchers_upgrade_cost = 0;
	    if ($torp_launchers_upgrade > $playerinfo['torp_launchers'])
	    {
			$torp_launchers_upgrade_cost = phpChangeDelta($torp_launchers_upgrade, $playerinfo['torp_launchers']);
	    }
		
	    $shields_upgrade_cost = 0;
	    if ($shields_upgrade > $playerinfo['shields'])
	    {
			$shields_upgrade_cost = phpChangeDelta($shields_upgrade, $playerinfo['shields']);
	    }

		if ($fighter_number < 0)
			$fighter_number = 0;
		
		$fighter_number = round(abs($fighter_number));
		$fighter_max = NUM_FIGHTERS($playerinfo['computer']) - $playerinfo['ship_fighters'];
		
		if ($fighter_max < 0)
			$fighter_max = 0;
		
		if ($fighter_number > $fighter_max)
			$fighter_number = $fighter_max;
		  
	    $fighter_cost = $fighter_number * $fighter_price;
	    
		if ($torpedo_number < 0)
			$torpedo_number = 0;
    
		$torpedo_number = round(abs($torpedo_number));
	    $torpedo_max = NUM_TORPEDOES($playerinfo['torp_launchers']) - $playerinfo['torps'];
	    
		if ($torpedo_max < 0)
			$torpedo_max = 0;
		  
	    if ($torpedo_number > $torpedo_max)
			$torpedo_number = $torpedo_max;
		  
	    $torpedo_cost = $torpedo_number * $torpedo_price;
	    
		if ($armor_number < 0)
			$armor_number = 0;
			
	    $armor_number = round(abs($armor_number));
	    $armor_max = NUM_ARMOUR($playerinfo['armor']) - $playerinfo['armor_pts'];

	    if($armor_max < 0)
			$armor_max = 0;
		  
	    if($armor_number > $armor_max)
			$armor_number = $armor_max;
		  
	    $armor_cost = $armor_number * $armor_price;
		
	    if($colonist_number < 0)
			$colonist_number = 0;
	    
		$colonist_number = round(abs($colonist_number));
	    $colonist_max = NUM_HOLDS($playerinfo['hull']) - $playerinfo['ship_ore'] - $playerinfo['ship_organics'] -
						$playerinfo['ship_goods'] - $playerinfo['ship_colonists'];

	    if($colonist_number > $colonist_max)
			$colonist_number = $colonist_max;

	    $colonist_cost            = $colonist_number * $colonist_price;
	    $dev_genesis_number       = round(abs($dev_genesis_number));
	    $dev_genesis_cost         = $dev_genesis_number * $dev_genesis_price;
	    $dev_beacon_number        = round(abs($dev_beacon_number));
	    $dev_beacon_cost          = $dev_beacon_number * $dev_beacon_price;
	    $dev_emerwarp_number      = min(round(abs($dev_emerwarp_number)), $max_emerwarp - $playerinfo['dev_emerwarp']);
	    $dev_emerwarp_cost        = $dev_emerwarp_number * $dev_emerwarp_price;
	    $dev_warpedit_number      = round(abs($dev_warpedit_number));
	    $dev_warpedit_cost        = $dev_warpedit_number * $dev_warpedit_price;
	    $dev_minedeflector_number = round(abs($dev_minedeflector_number));
	    $dev_minedeflector_cost   = $dev_minedeflector_number * $dev_minedeflector_price;

	    $dev_escapepod_cost = 0;
	    $dev_fuelscoop_cost = 0;
	    $dev_lssd_cost = 0;
	
	    if (($escapepod_purchase) && ($playerinfo['dev_escapepod'] != 'Y'))
			$dev_escapepod_cost = $dev_escapepod_price;
		
	    if (($fuelscoop_purchase) && ($playerinfo['dev_fuelscoop'] != 'Y'))
			$dev_fuelscoop_cost = $dev_fuelscoop_price;
			
	    if(($lssd_purchase) && ($playerinfo['dev_lssd'] != 'Y'))
			$dev_lssd_cost = $dev_lssd_price;
		  
	    $total_cost =	$hull_upgrade_cost + $engine_upgrade_cost + $power_upgrade_cost + $computer_upgrade_cost +
						$sensors_upgrade_cost + $beams_upgrade_cost + $armor_upgrade_cost + $cloak_upgrade_cost +
						$torp_launchers_upgrade_cost + $fighter_cost + $torpedo_cost + $armor_cost + $colonist_cost +
						$dev_genesis_cost + $dev_beacon_cost + $dev_emerwarp_cost + $dev_warpedit_cost + $dev_minedeflector_cost +
						$dev_escapepod_cost + $dev_fuelscoop_cost + $dev_lssd_cost + $shields_upgrade_cost;

		if ($total_cost > $playerinfo['credits'])
			echo 'You do not have enough credits for this transaction.  The total cost is ',  NUMBER($total_cost), ' credits and you only have ', NUMBER($playerinfo['credits']), ' credits.<br><br>Click <a href=', $scripturl, '?action=blacknova;sa=port>here</a> to return to the supply depot.<br><br>';
	    else
	    {
			$trade_credits = NUMBER(abs($total_cost));
			
			echo '
				<table border=2 cellspacing=2 cellpadding=2 bgcolor=#400040 width=600 align=center>
					<tr>
						<td colspan=99 align=center bgcolor=#300030><font size=3 color=white><b>', $txt['bnt_trade_result'], '</b></font></td>
					</tr>
					<tr>
						<td colspan=99 align=center><b><font color=red>', $txt['bnt_cost'],' : ',  $trade_credits, ' ', $txt['bnt_credits'], '</font></b></td>
					</tr>';

			//  Total cost is " . NUMBER(abs($total_cost)) . " credits.<BR><BR>";
			
			$query = "UPDATE " . $dbtables['ships'] . " SET credits = credits - " . $total_cost;
			
			if ($hull_upgrade > $playerinfo['hull'])
			{
				$tempvar = 0;
				$tempvar = phpTrueDelta($hull_upgrade, $playerinfo['hull']);
				$query .= ", hull = hull + " . $tempvar;
				BuildOneCol("$txt[bnt_hull] $txt[bnt_trade_upgraded] $hull_upgrade");
			}
			
			if ($engine_upgrade > $playerinfo['engines'])
			{
				$tempvar = 0;
				$tempvar = phpTrueDelta($engine_upgrade, $playerinfo['engines']);
				$query .= ", engines = engines + " . $tempvar;
				BuildOneCol("$txt[bnt_engines] $txt[bnt_trade_upgraded] $engine_upgrade");
			}
			
			if ($power_upgrade > $playerinfo['power'])
			{
				$tempvar = 0;
				$tempvar = phpTrueDelta($power_upgrade, $playerinfo['power']);
				$query .= ", power = power + " . $tempvar;
				BuildOneCol("$txt[bnt_power] $txt[bnt_trade_upgraded] $power_upgrade");
			}
			
			if ($computer_upgrade > $playerinfo['computer'])
			{
				$tempvar = 0;
				$tempvar = phpTrueDelta($computer_upgrade, $playerinfo['computer']);
				$query .= ", computer = computer + " . $tempvar;
				BuildOneCol("$txt[bnt_computer] $txt[bnt_trade_upgraded] $computer_upgrade");
			}
			
			if ($sensors_upgrade > $playerinfo['sensors'])
			{
				$tempvar = 0;
				$tempvar = phpTrueDelta($sensors_upgrade, $playerinfo['sensors']);
				$query .= ", sensors = sensors + " . $tempvar;
				BuildOneCol("$txt[bnt_sensors] $txt[bnt_trade_upgraded] $sensors_upgrade");
			}
			
			if ($beams_upgrade > $playerinfo['beams'])
			{
				$tempvar = 0;
				$tempvar = phpTrueDelta($beams_upgrade, $playerinfo['beams']);
				$query .= ", beams = beams + " . $tempvar;
				BuildOneCol("$txt[bnt_beams] $txt[bnt_trade_upgraded] $beams_upgrade");
			}
			
			if ($armor_upgrade > $playerinfo['armor'])
			{
				$tempvar = 0;
				$tempvar = phpTrueDelta($armor_upgrade, $playerinfo['armor']);
				$query .= ", armor = armor + " . $tempvar;
				BuildOneCol("$txt[bnt_armor] $txt[bnt_trade_upgraded] $armor_upgrade");
			}
			
			if ($cloak_upgrade > $playerinfo['cloak'])
			{
				$tempvar = 0;
				$tempvar = phpTrueDelta($cloak_upgrade, $playerinfo['cloak']);
				$query .= ", cloak = cloak + " . $tempvar;
				BuildOneCol("$txt[bnt_cloak] $txt[bnt_trade_upgraded] $cloak_upgrade");
			}
			
			if ($torp_launchers_upgrade > $playerinfo['torp_launchers'])
			{
				$tempvar = 0;
				$tempvar = phpTrueDelta($torp_launchers_upgrade, $playerinfo['torp_launchers']);
				$query .= ", torp_launchers = torp_launchers + " . $tempvar;
				BuildOneCol("$txt[bnt_torp_launch] $txt[bnt_trade_upgraded] $torp_launchers_upgrade");
			}
			
			if ($shields_upgrade > $playerinfo['shields'])
			{
				$tempvar = 0;
				$tempvar = phpTrueDelta($shields_upgrade, $playerinfo['shields']);
				$query .= ", shields = shields + " . $tempvar;
				BuildOneCol("$txt[bnt_shields] $txt[bnt_trade_upgraded] $shields_upgrade");
			}
			
			if ($fighter_number)
			{
				$query .= ", ship_fighters = ship_fighters + " . $fighter_number;
				BuildTwoCol("$txt[bnt_fighters] $txt[bnt_trade_added]:", $fighter_number, "left", "right" );
			}
			
			if ($torpedo_number)
			{
				$query .= ", torps = torps + " . $torpedo_number;
				BuildTwoCol("$txt[bnt_torps] $txt[bnt_trade_added]:", $torpedo_number, "left", "right" );
			}
			
			if ($armor_number)
			{
				$query .= ", armor_pts = armor_pts + " . $armor_number;
				BuildTwoCol("$txt[bnt_armorpts] $txt[bnt_trade_added]:", $armor_number, "left", "right" );
			}
			
			if ($colonist_number)
			{
				$query .= ", ship_colonists = ship_colonists + " . $colonist_number;
				BuildTwoCol("$txt[bnt_colonists] $txt[bnt_trade_added]:", $colonist_number, "left", "right" );
			}
			
			if ($dev_genesis_number)
			{
				$query .= ", dev_genesis = dev_genesis + " . $dev_genesis_number;
				BuildTwoCol("$txt[bnt_genesis] $txt[bnt_trade_added]:", $dev_genesis_number, "left", "right" );
			}
			
			if ($dev_beacon_number)
			{
				$query .= ", dev_beacon = dev_beacon + " . $dev_beacon_number;
				BuildTwoCol("$txt[bnt_beacons] $txt[bnt_trade_added]:", $dev_beacon_number , "left", "right" );
			}
			
			if ($dev_emerwarp_number)
			{
				$query .= ", dev_emerwarp = dev_emerwarp + " . $dev_emerwarp_number;
				BuildTwoCol("$txt[bnt_ewd] $txt[bnt_trade_added]:", $dev_emerwarp_number , "left", "right" );
			}
			
			if ($dev_warpedit_number)
			{
				$query .= ", dev_warpedit = dev_warpedit + " . $dev_warpedit_number;
				BuildTwoCol("$txt[bnt_warpedit] $txt[bnt_trade_added]:", $dev_warpedit_number , "left", "right" );
			}
			
			if ($dev_minedeflector_number)
			{
				$query .= ", dev_minedeflector = dev_minedeflector + " . $dev_minedeflector_number;
				BuildTwoCol("$txt[bnt_deflect] $txt[bnt_trade_added]:", $dev_minedeflector_number , "left", "right" );
			}
			
			if (($escapepod_purchase) && ($playerinfo['dev_escapepod'] != 'Y'))
			{
				$query .= ", dev_escapepod = 'Y'";
				BuildOneCol("$txt[bnt_escape_pod] $txt[bnt_trade_installed]");
			}
			
			if (($fuelscoop_purchase) && ($playerinfo['dev_fuelscoop'] != 'Y'))
			{
				$query .= ", dev_fuelscoop = 'Y'";
				BuildOneCol("$txt[bnt_fuel_scoop] $txt[bnt_trade_installed]");
			}
			
			if (($lssd_purchase) && ($playerinfo['dev_lssd'] != 'Y'))
			{
				$query .= ", dev_lssd = 'Y'";
				BuildOneCol("$txt[bnt_lssd] $txt[bnt_trade_installed]");
			}
			
			$query .= ", turns = turns - 1, turns_used = turns_used + 1 WHERE ship_id = " . $playerinfo['ship_id'];
			
			$update = $smcFunc['db_query']('',
				$query,
				array(
					'db_ships' => $dbtables['ships']
				)
			);
			$hull_upgrade = 0;
			echo '</table>';
	    }
	}
	elseif ($sectorinfo['port_type'] != "none")
	{
		/*
		  Here is the TRADE fonction to strip out some "spaghetti code".
		  The function saves about 60 lines of code, I hope it will be
		  easier to modify/add something in this part.
			--Fant0m
		*/
		
		if (isset($_POST['trade_ore']))
			$trade_ore = $_POST['trade_ore'];
		else
			die();
		if (isset($_POST['trade_organics']))
			$trade_organics = $_POST['trade_organics'];
		else
			die();
		if (isset($_POST['trade_goods']))
			$trade_goods = $_POST['trade_goods'];
		else
			die();
		if (isset($_POST['trade_energy']))
			$trade_energy = $_POST['trade_energy'];
		else
			die();
			
		$trade_ore      = round(abs($trade_ore));
		$trade_organics = round(abs($trade_organics));
		$trade_goods    = round(abs($trade_goods));
		$trade_energy   = round(abs($trade_energy));
		
		function TRADE($price, $delta, $max, $limit, $factor, $port_type, $origin, $sector_port_type)
		{	
			global $debug;
			
			if ($sector_port_type ==  $port_type )
			{
				$price_array[$port_type] = $price - $delta * $max / $limit * $factor;
				$price_array['origin'] = $origin;
			}
			else
			{
				$price_array[$port_type] = $price + $delta * $max / $limit * $factor;
				$price_array['origin'] = -$origin;
			}
			
			if ($debug)
			{
				echo "$price_array[origin]*$price_array[$port_type]=";
				echo $price_array['origin']*$price_array[$port_type]."<br>";
			}
				
			return $price_array;
		}


		$trade_ore       =  TRADE($ore_price,        $ore_delta,       $sectorinfo['port_ore'],        $ore_limit,       $inventory_factor, "ore",        $trade_ore,		$sectorinfo['port_type']);
		$trade_organics  =  TRADE($organics_price,   $organics_delta,  $sectorinfo['port_organics'],   $organics_limit,  $inventory_factor, "organics",   $trade_organics,	$sectorinfo['port_type']);
		$trade_goods     =  TRADE($goods_price,      $goods_delta,     $sectorinfo['port_goods'],      $goods_limit,     $inventory_factor, "goods",      $trade_goods,		$sectorinfo['port_type']);
		$trade_energy    =  TRADE($energy_price,     $energy_delta,    $sectorinfo['port_energy'],     $energy_limit,    $inventory_factor, "energy",     $trade_energy,	$sectorinfo['port_type']);

		$ore_price       =  $trade_ore['ore'];
		$organics_price  =  $trade_organics['organics'];
		$goods_price     =  $trade_goods['goods'];
		$energy_price    =  $trade_energy['energy'];
		
		$trade_ore 		 =  $trade_ore['origin'];
		$trade_organics	 =  $trade_organics['origin'];
		$trade_goods	 =  $trade_goods['origin'];
		$trade_energy    =  $trade_energy['origin'];

		$cargo_exchanged = $trade_ore + $trade_organics + $trade_goods;

		$free_holds =	NUM_HOLDS($playerinfo['hull']) - $playerinfo['ship_ore'] - $playerinfo['ship_organics'] -
						$playerinfo['ship_goods'] - $playerinfo['ship_colonists'];
		$free_power = 	NUM_ENERGY($playerinfo['power']) - $playerinfo['ship_energy'];
		$total_cost =	$trade_ore * $ore_price + $trade_organics * $organics_price + $trade_goods * $goods_price +
						$trade_energy * $energy_price;
		
		if ($debug)
			echo "$trade_ore * $ore_price + $trade_organics * $organics_price + $trade_goods * $goods_price + $trade_energy * $energy_price = $total_cost";

		if ($free_holds < $cargo_exchanged)
			echo $txt['bnt_notenough_cargo'], '  ', $txt['bnt_returnto_port'], '<br><br>';
		
		elseif ($trade_energy > $free_power)
			echo $txt['bnt_notenough_power'], '  ', $txt['bnt_returnto_port'], '<br><br>';
		
		elseif ($playerinfo['turns'] < 1)
			echo $txt['bnt_notenough_turns'], '.<br><br>';
		
		elseif ($playerinfo['credits'] < $total_cost)
			echo $txt['bnt_notenough_credits'], '<br><br>';
		
		elseif ($trade_ore < 0 && abs($playerinfo['ship_ore']) < abs($trade_ore))
			echo $txt['bnt_notenough_ore'], ' ';
		
		elseif ($trade_organics < 0 && abs($playerinfo['ship_organics']) < abs($trade_organics))
			echo $txt['bnt_notenough_organics'], ' ';
		
		elseif ($trade_goods < 0 && abs($playerinfo['ship_goods']) < abs($trade_goods))
			echo $txt['bnt_notenough_goods'], ' ';
		
		elseif ($trade_energy < 0 && abs($playerinfo['ship_energy']) < abs($trade_energy))
			echo $txt['bnt_notenough_energy'], ' ';
		
		elseif (abs($trade_organics) > $sectorinfo['port_organics'])
			echo $txt['bnt_exceed_organics'];
		
		elseif (abs($trade_ore) > $sectorinfo['port_ore'])
			echo $txt['bnt_exceed_ore'];
		
		elseif (abs($trade_goods) > $sectorinfo['port_goods'])
			echo $txt['bnt_exceed_goods'];
		
		elseif (abs($trade_energy) > $sectorinfo['port_energy'])
			echo $txt['bnt_exceed_energy'];
		
		else
		{
			if ($total_cost == 0 )
			{
				$trade_color   = "white";
				$trade_result  = "$txt[bnt_cost] : ";
			}
			elseif ($total_cost < 0 )
			{
				$trade_color   = $color_green;
				$trade_result  = $trade_benefit;
			}
			else
			{
				$trade_color   = $color_red;
				$trade_result  = $trade_deficit;
			}
			
			// Display Trade Result table.
			echo '
			<table border=2 cellspacing=2 cellpadding=2 bgcolor=#400040 width=600 align=center>
				<tr>
					<td colspan=99 align=center><font size=3 color=white><b>', $txt['bnt_trade_result'], '</b></font></td>
				</tr>
				<tr>
					<td colspan=99 align=center><b><font color="', $trade_color, '">', $trade_result ,' ', NUMBER(abs($total_cost)), ' ', $txt['bnt_credits'], '</font></b></td>
				</tr>
				<tr bgcolor=', $color_line1, '>
					<td><b><font size=2 color=white>', $txt['bnt_traded_ore'], ': </font><b></td><td align=right><b><font size=2 color=white>', NUMBER($trade_ore), '</font></b></td>
				</tr>
				<tr bgcolor=', $color_line2, '>
					<td><b><font size=2 color=white>', $txt['bnt_traded_organics'], ': </font><b></td><td align=right><b><font size=2 color=white>', NUMBER($trade_organics), '</font></b></td>
				</tr>
				<tr bgcolor=', $color_line1, '>
					<td><b><font size=2 color=white>', $txt['bnt_traded_goods'], ': </font><b></td><td align=right><b><font size=2 color=white>', NUMBER($trade_goods), '</font></b></td>
				</tr>
				<tr bgcolor=', $color_line2, '>
					<td><b><font size=2 color=white>', $txt['bnt_traded_energy'], ': </font><b></td><td align=right><b><font size=2 color=white>', NUMBER($trade_energy), '</font></b></td>
				</tr>
			</table>';
			
			// Update ship cargo, credits and turns
			$trade_result = $smcFunc['db_query']('', '
				UPDATE {raw:db_ships}
				SET turns = turns - 1,
					turns_used = turns_used + 1,
					rating = rating + 1,
					credits = credits - {float:total_cost},
					ship_ore = ship_ore + {float:trade_ore},
					ship_organics = ship_organics + {float:trade_organics},
					ship_goods = ship_goods + {float:trade_goods},
					ship_energy = ship_energy + {float:trade_energy}
					WHERE ship_id = {int:ship_id}',
				array(
					'db_ships' => $dbtables['ships'],
					'ship_id' => $playerinfo['ship_id'],
					'total_cost' => round($total_cost),
					'trade_ore' => round($trade_ore),
					'trade_organics' => round($trade_organics),
					'trade_goods' => round($trade_goods),
					'trade_energy' => round($trade_energy)
				)
			);
		
			/* Make all trades positive to change port values*/
			$trade_ore        = round(abs($trade_ore));
			$trade_organics   = round(abs($trade_organics));
			$trade_goods      = round(abs($trade_goods));
			$trade_energy     = round(abs($trade_energy));

			/* Decrease supply and demand on port */
			$trade_result = $smcFunc['db_query']('', '
				UPDATE {raw:db_universe}
				SET port_ore = port_ore - {int:trade_ore},
					port_organics = port_organics - {int:trade_organics},
					port_goods = port_goods - {int:trade_goods},
					port_energy = port_energy - {int:trade_energy}
					WHERE sector_id = {int:sector_id}',
				array(
					'db_universe' => $dbtables['universe'],
					'sector_id' => $sectorinfo['sector_id'],
					'trade_ore' => $trade_ore,
					'trade_organics' => $trade_organics,
					'trade_goods' => $trade_goods,
					'trade_energy' => $trade_energy
				)
			);
			
			echo $txt['bnt_trade_complete'], '.<br><br>';
		}
	}
}

//-------------------------------------------------------------------------------------------------

echo '<br><br>';

if ($sectorinfo['port_type'] == "special")
	echo '<br><br>Click <a href=', $scripturl, '?action=blacknova;sa=port>here</a> to return to the supply depot.';

TextMainMenu();
?>
